package game.components;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Timer;

public class GameTimer {
	private long startTime = 0;
	private SimpleDateFormat formatDate;
	private Timer timer;
	private int count = 0;
	private JLabel jLabel;
	private long elapsed;

	public GameTimer(JLabel jLabel) {
		this.jLabel = jLabel;
		ClockAction clockAciton = new ClockAction();
		this.timer = new Timer(1000, clockAciton);
		this.formatDate = new SimpleDateFormat("mm:ss");

		// init
		this.timer.setInitialDelay(1000);
	}

	public static void main(String[] args) {
		JLabel lbl = new JLabel();
		GameTimer gameTimer = new GameTimer(lbl);
		gameTimer.startCount();
		lbl.setBounds(0, 0, 100, 40);

		// main frame
		JFrame jFrame = new JFrame();
		jFrame.setBounds(100, 80, 240, 120);
		jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		jFrame.getContentPane().setLayout(new GridLayout(1, 1));
		jFrame.setVisible(true);

		// add components
		jFrame.add(lbl);
	}

	public void startCount() {
		this.startTime = System.currentTimeMillis();
		this.timer.start();
	}

	public void stopCount() {
		this.timer.stop();
		this.startTime = elapsed;
		this.count = 0;
	}

	public void resetCount() {
		stopCount();
		this.startTime = 0;
	}

	private void updateTime() {
		this.elapsed = System.currentTimeMillis() - startTime;
		this.count++;

		// -------------------------------------------------------------
		// Set component text
		// -------------------------------------------------------------
		Date date = new Date(elapsed);
		String text = this.formatDate.format(date);
		jLabel.setText(text);
		// -------------------------------------------------------------
	}

	public int getCount() {
		return count;
	}

	public Timer getTimer() {
		return timer;
	}

	class ClockAction implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			updateTime();
		}
	}
}
